package com.lanou.sfu.songforu.music_bd;


import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.os.RemoteException;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.lanou.sfu.songforu.activity.MainActivity;
import com.lanou.sfu.songforu.datas.MusicListDatas;
import com.lanou.sfu.songforu.datas.SongInfors;
import com.lanou.sfu.songforu.singleton.VolleySingleton;
import com.lanou.sfu.songforu.view.MyEvent;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class MusicService extends Service {

    // 定义一个播放对象
    private MediaPlayer mMediaPlayer;
    //网络
    private List<MusicListDatas> listDatases = new ArrayList<>();
    private List<ManaMusic> mList = null;//本地
    private MusicListDatas musicListDatas;
    private String songid;
    private int position;
    private String pic_small, name, songLink, auther;
    private VolleySingleton volleySingleton;
    private MyEvent.MusicDatasEvent datasEvent;
    private int mNowPlayIndex = 0;
    private String songurl;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        //setDataSource();
        return mBinder;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        EventBus.getDefault().register(this);
        mMediaPlayer = new MediaPlayer();
        volleySingleton = VolleySingleton.getInstance(getApplicationContext());
        datasEvent = new MyEvent.MusicDatasEvent();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mMediaPlayer.start();
            }
        });
        mList = ManaListAdapter.mList;
        super.onCreate();
    }

    public void onEvent(final MyEvent.MusicDatasEvent datasEvent) {
        listDatases = datasEvent.getListDatases();
        position = listDatases.get(0).getPosition();
        for (int i = 0; i < listDatases.size(); i++) {
            final int key = i;
            songid = listDatases.get(i).getSongId();
            final String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.song.getInfos&format=json&songid=" +
                    songid + "&ts=1445399459391&e=SmJtjLwgnuWRzBbIIHeXgNusY1L" +
                    "%2FXZoWyOitaQ3ExdPXWpSPZ0Fras1q%2FLVxivZr&nw=2&fr=sns&ucf=1&res=1&l2p=2943&lpb=&usup=1&lebo=0";
            JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    String str = response.toString();
                    SongInfors infors = JSON.parseObject(str, SongInfors.class);
//                String url = infors.getSongurl().getUrl().get(1).getShow_link();
                    songurl = !infors.getSongurl().getUrl().get(0).getShow_link().isEmpty() ? infors.getSongurl().getUrl().get(0).getShow_link() : infors.getSongurl().getUrl().get(1).getShow_link();
//					mMediaPlayer.reset();
//					mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//					//加载多媒体文件
//					try {mMediaPlayer.setDataSource(url);
//						 mMediaPlayer.prepareAsync();

//					} catch (IOException e) {
//						e.printStackTrace();
//					}


                    if (listDatases.get(key).getUrl() != null) {
                        setDataSource();
                        datasEvent.setListDatases(listDatases);
                        EventBus.getDefault().post(datasEvent);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
            volleySingleton.addQueue(jr, "PlayerService");
        }
        if (listDatases.get(position).getUrl() != null) {
            mNowPlayIndex = position;
            setDataSource();
            mMediaPlayer.start();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        if (mMediaPlayer.isPlaying()) {
            sendReceiverUpdateUI();
        } else {
            setDataSource();
        }
        return super.onStartCommand(intent, flags, startId);
    }


    // 设置资源
    void setDataSource() {
        try {
            mMediaPlayer.reset(); // 重新实例化
            mMediaPlayer.setOnPreparedListener(null);
            mMediaPlayer.setDataSource(listDatases.get(mNowPlayIndex).getUrl()); //设置需要加载的文件
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); // 设置音频流
            mMediaPlayer.prepareAsync();  //储卡中内容加载或者网络中的部分媒体内容加载到内存中

        } catch (IOException ex) {
            // TODO: notify the user why the file couldn't be opened

            return;
        } catch (IllegalArgumentException ex) {
            // TODO: notify the user why the file couldn't be opened

            return;
        }

        mMediaPlayer.setOnCompletionListener(mMusicCompletionListener);
        sendReceiverUpdateUI();
    }

    MediaPlayer.OnCompletionListener mMusicCompletionListener = new MediaPlayer.OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer arg0) {
            // TODO Auto-generated method stub
            playNextMusic();
        }

    };

    /**
     * 播放下一曲歌曲
     */
    private void playNextMusic() {
        if (mNowPlayIndex + 1 > mList.size() - 1) {
            mNowPlayIndex = 0;
        } else {
            mNowPlayIndex++;
        }

        setDataSource();

        mMediaPlayer.start();
    }

    private void sendReceiverUpdateUI() {
//		Intent i = new Intent(MainActivity.UPDATE_UI);
//		sendBroadcast(i);
    }

    /**
     * 实现aidl的接口
     */
    private final IMusicBackService.Stub mBinder = new IMusicBackService.Stub() {

        // 返回当前播放到位置
        @Override
        public int getNowPlayingMusicCurTime() throws RemoteException {
            // TODO Auto-generated method stub
            return mMediaPlayer.getCurrentPosition();
        }

        // 返回当前音频长度
        @Override
        public int getNowPlayingMusicMaxTime() throws RemoteException {
            // TODO Auto-generated method stub
            return mMediaPlayer.getDuration();
        }


        //是否在播放音乐
        @Override
        public boolean getMusicIsPlaying() throws RemoteException {
            // TODO Auto-generated method stub
            return mMediaPlayer.isPlaying();
        }

        // 暂停播放
        @Override
        public void stopMusic() throws RemoteException {
            // TODO Auto-generated method stub
            System.out.println("start");
            mMediaPlayer.pause();
        }

        // 开始播放
        @Override
        public void playMusic() throws RemoteException {
            // TODO Auto-generated method stub
            System.out.println("start");
            mMediaPlayer.start();

        }

        @Override
        public void playUpMusic() throws RemoteException {
            // TODO Auto-generated method stub
            if (mNowPlayIndex - 1 < 0) {
                mNowPlayIndex = mList.size() - 1;
            } else {
                mNowPlayIndex--;
            }
            setDataSource();
            mMediaPlayer.start();
        }


        // 播放下一首
        @Override
        public void playNextMusic() throws RemoteException {
            // TODO Auto-generated method stub
            playNextMusic();
        }

        @Override
        public void setNowPlay(int time) throws RemoteException {
            // TODO Auto-generated method stub
            mNowPlayIndex = time;
        }

        //获取当前播放歌曲的id
        @Override
        public int getNowPlay() throws RemoteException {
            // TODO Auto-generated method stub
            return mNowPlayIndex;
        }

        //设置资源并播放
        @Override
        public void setDataSourceAndPlay() throws RemoteException {
            // TODO Auto-generated method stub
            setDataSource();
            mMediaPlayer.start();
        }

        //播放位置
        @Override
        public void setProgress(int progress) throws RemoteException {
            // TODO Auto-generated method stub
            mMediaPlayer.seekTo(progress);
        }

        @Override
        public void pauseMusic() throws RemoteException {
            mMediaPlayer.pause();
        }
    };

    @Override
    public void onDestroy() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
